package com.kkshop.test.fixture;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCallback;
import org.springframework.jdbc.core.PreparedStatementCreator;

public class NewCustomerFixture extends NewUserFixture {

	private static final String INSERT_CUSTOMER_SQL = "INSERT INTO customers VALUES (?, ?)";
	private static final String DELETE_CUSTOMER_SQL = "DELETE FROM customers WHERE id = ?";
	
	protected long id;

	public NewCustomerFixture(DataSource dataSource, long id, String username, String password, String role, boolean enabled) {
		super(dataSource, username, password, role, enabled);
		this.id = id;
	}
	
	public void setUp() throws Exception {
		super.setUp();
		JdbcTemplate template = new JdbcTemplate(dataSource);
		template.execute(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
				PreparedStatement statement = connection.prepareStatement(INSERT_CUSTOMER_SQL);
				statement.setLong(1, id);
				statement.setString(2, username);
				return statement;
			}
		}, new PreparedStatementCallback() {
			public Object doInPreparedStatement(PreparedStatement statement) throws SQLException, DataAccessException {
				statement.execute();
				return null;
			}
		});
	}

	public void tearDown() throws Exception {
		JdbcTemplate template = new JdbcTemplate(dataSource);
		template.execute(new PreparedStatementCreator() {
			public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
				PreparedStatement statement = connection.prepareStatement(DELETE_CUSTOMER_SQL);
				statement.setLong(1, id);
				return statement;
			}
		}, new PreparedStatementCallback() {
			public Object doInPreparedStatement(PreparedStatement statement) throws SQLException, DataAccessException {
				statement.execute();
				return null;
			}
		});
		super.tearDown();
	}
}
